package com.mes.cloud.domain.util;

import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

/**
 * @author hu 日期信息处理
 */

public class DateUtils {
    public final static String defaultPattern = "yyyy-MM-dd";
    public final static String defaultTimeHMSPattern = "HH:mm:ss";
    public final static String dateTimePattern = "yyyy-MM-dd HH:mm";
    private final static String dateMonthHourPattern = "M月d日HH:mm";
    public final static String dateMonthPattern = "yyyy年MM月dd日";
    public final static String dateTimeSecondPattern = "yyyy-MM-dd HH:mm:ss";
    public final static String dateTimeYNDPattern = "yyyy年MM月dd日HH点mm分";
    public final static String dateTimeYNDHMSPattern = "yyyyMMddHHmmss";
    public final static String dateYNDPattern = "yyyyMMdd";
    private final static ThreadLocal<HashMap<String, SimpleDateFormat>> customerMapThread = new ThreadLocal<HashMap<String, SimpleDateFormat>>();

    /**
     * Description: 获取日历对象 @Version1.0 2015-2-26 下午2:28:35 by
     * 张四有(sy.zhang01@zuche.com)
     * 
     * @return
     */
    public static Calendar getCalendar() {
	return Calendar.getInstance();
    }

    /**
     * Description: 获取当前时间的毫秒 @Version1.0 2015-2-26 下午2:28:55 by
     * 张四有(sy.zhang01@zuche.com)
     * 
     * @return
     */
    public static long getNowTime() {
	return getCalendar().getTimeInMillis();
    }

    /**
     * Description: 获取当前日期 @Version1.0 2015-2-26 下午2:30:19 by
     * 张四有(sy.zhang01@zuche.com)
     * 
     * @return
     */
    public static Date getNowDate() {
	return getCalendar().getTime();
    }

    public static int getNowYear() {
	return getCalendar().get(Calendar.YEAR);
    }

    public static String getNowMonth() {
	Integer month = getCalendar().get(Calendar.MONTH) + 1;
	return (month < 10 ? ("0" + month.toString()) : (month.toString()));
    }

    /**
     * Description: 获取给定格式的时间 @Version1.0 2015-2-26 下午2:44:35 by
     * 张四有(sy.zhang01@zuche.com)
     * 
     * @param pattern
     * @return
     */
    public static String getFormateDate(String pattern) {
	if (StringUtils.isEmpty(pattern)) {
	    pattern = defaultPattern;
	}
	SimpleDateFormat sdf = new SimpleDateFormat(pattern);
	return sdf.format(getNowDate());
    }

    /**
     * Description: 获取默认格式的时间 @Version1.0 2015-2-26 下午2:45:08 by
     * 张四有(sy.zhang01@zuche.com)
     * 
     * @return
     */
    public static String getDefaultFormateDate() {

	return getFormateDate(defaultPattern);
    }

    /**
     * 根据传入字符串 返回yyyy年mm月dd日,月份日期为单位时显示为双位
     */
    public static String getCurrentDateToCNWhole(String dateTime) {

	String year = dateTime.substring(0, 4);
	String month;
	String day;

	month = dateTime.substring(5, 7);
	day = dateTime.substring(8, 10);
	return year + "年" + month + "月" + day + "日";
    }

    /**
     * Description: 将日期字符串转换成日期型
     *
     * @param dateStr
     * @return @Version1.0 2012-11-5 上午08:50:21 by 万久卫（jw.wan@zuche.com）
     */
    public static Date dateString2Date(String dateStr) {
	return dateString2Date(dateStr, defaultPattern);
    }

    /**
     * Description: 将日期字符串转换成指定格式日期
     *
     * @param dateStr
     * @param partner
     * @return @Version1.0 2012-11-5 上午08:50:55 by 万久卫（jw.wan@zuche.com）
     */
    public static Date dateString2Date(String dateStr, String partner) {

	try {
	    SimpleDateFormat formatter = getSimpleDateFormat(partner);
	    ParsePosition pos = new ParsePosition(0);
	    return formatter.parse(dateStr, pos);
	} catch (NullPointerException e) {
	    return null;
	}
    }

    /**
     * 获取指定日期的年份
     *
     * @param p_date
     *            util.Date日期
     * @return int 年份
     */
    public static int getYearOfDate(Date p_date) {
	Calendar c = Calendar.getInstance();
	c.setTime(p_date);
	return c.get(Calendar.YEAR);
    }

    /**
     * Description: 获取日期字符串的年份
     *
     * @param p_date
     *            字符串日期
     * @return int 年份 @Version1.0 2012-11-5 上午08:51:51 by 万久卫（jw.wan@zuche.com）
     */
    public static int getYearOfDate(String p_date) {
	return getYearOfDate(dateString2Date(p_date));
    }

    /**
     * Description: 获取指定日期的月份
     *
     * @param p_date
     *            java.util.Date
     * @return int 月份 @Version1.0 2012-11-5 上午08:52:14 by 万久卫（jw.wan@zuche.com）
     */
    public static int getMonthOfDate(Date p_date) {
	Calendar c = Calendar.getInstance();
	c.setTime(p_date);
	return c.get(Calendar.MONTH) + 1;
    }

    /**
     * Description: 获取日期字符串的月份
     *
     * @param date
     *            字符串日期
     * @return int 月份 @Version1.0 2012-11-5 上午08:53:22 by 万久卫（jw.wan@zuche.com）
     */
    public static int getMonthOfDate(String date) {
	return getMonthOfDate(dateString2Date(date));
    }

    /**
     * 获取指定日期的日份
     *
     * @param p_date
     *            util.Date日期
     * @return int 日份
     */
    public static int getDayOfDate(Date p_date) {
	Calendar c = Calendar.getInstance();
	c.setTime(p_date);
	return c.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * 获取指定日期的周 与 Date .getDay()兼容
     *
     * @param date
     *            String 日期
     * @return int 周
     */
    public static int getWeekOfDate(String date) {
	Date p_date = dateString2Date(date);
	return getWeekOfDate(p_date);
    }

    /**
     * 获取指定日期的周 与 Date .getDay()兼容
     *
     * @param date
     *            util.Date日期
     * @return int 周
     */
    public static int getWeekOfDate(Date date) {
	Calendar c = Calendar.getInstance();
	c.setTime(date);
	return c.get(Calendar.DAY_OF_WEEK) - 1;
    }

    /**
     * 获取指定日期的小时
     *
     * @param p_date
     *            util.Date日期
     * @return int 日份
     */
    public static int getHourOfDate(Date p_date) {
	Calendar c = Calendar.getInstance();
	c.setTime(p_date);
	return c.get(Calendar.HOUR_OF_DAY);
    }

    /**
     * 获取指定日期的分钟
     *
     * @param p_date
     *            util.Date日期
     * @return int 分钟
     */
    public static int getMinuteOfDate(Date p_date) {
	Calendar c = Calendar.getInstance();
	c.setTime(p_date);
	return c.get(Calendar.MINUTE);
    }

    /**
     * Description: 日期转化指定格式的字符串型日期
     *
     * @param p_utilDate
     *            java.util.Date
     * @param p_format
     *            日期格式
     * @return 字符串格式日期 @Version1.0 2012-11-5 上午08:58:44 by 万久卫（jw.wan@zuche.com）
     */
    public static String date2String(Date p_utilDate, String p_format) {
	String l_result = "";
	if (p_utilDate != null) {
	    SimpleDateFormat sdf = getSimpleDateFormat(p_format);
	    l_result = sdf.format(p_utilDate);
	}
	return l_result;
    }

    public static String date2String(Date p_utilDate) {
	return date2String(p_utilDate, defaultPattern);
    }

    /**
     * 
     * <p>
     * 方法说明:
     * <p>
     * TODO 时间字符转换20150101 转 2015-01-01
     *
     * @param str
     * @return
     */
    public static String strFormatStr(String str, String parm) {
	if (str != null & str.length() == 8) {
	    if (str.equals("00000000")) {
		return "";
	    }
	    if (parm.equals("")) {
		parm = "-";
	    }
	    String year = str.substring(0, 4);
	    String month = str.substring(4, 6);
	    String day = str.substring(6, 8);
	    return year + parm + month + parm + day;
	}
	return "";
    }

    public static String strFormatC(String str) {
	if (str != null && str.length() >= 8) {
	    String year = str.substring(0, 4);
	    String month = str.substring(5, 7);
	    String day = str.substring(8, 10);
	    return year + "年" + month + "月" + day + "日";
	}
	return null;
    }

    public static String getNowDateStr(int type) {
	if (type == 1) {
	    return date2String(getNowDate(), dateYNDPattern);
	} else if (type == 2) {
	    return date2String(getNowDate(), dateTimeYNDHMSPattern);
	} else if (type == 3) {// yyyy-mm-dd
	    return date2String(getNowDate(), defaultPattern);
	}
	return date2String(getNowDate(), dateTimeSecondPattern);
    }

    /**
     * @param @param
     *            p_date
     * @param @return
     * @return boolean
     * @throws @Title:
     *             checkWeekendDay
     * @Description: 判断是平时还是周末
     */

    public static boolean checkWeekendDay(String p_date) {
	Calendar c = Calendar.getInstance();
	c.setTime(dateString2Date(p_date));
	int num = c.get(Calendar.DAY_OF_WEEK);

	// 如果为周六 周日则为周末 1星期天 2为星期六
	return num == 6 || num == 7 || num == 1;
    }

    /**
     * @param @param
     *            startTime
     * @param @param
     *            endTime
     * @param @return
     * @param @throws
     *            ParseException
     * @return String[][]
     * @throws @Title:
     *             getMonthsByTime
     * @Description: 按时间段计算月份跨度 计算出所包含的月份
     */
    @SuppressWarnings("static-access")
    public static int[][] getMonthsByTime(String startTime, String endTime) {
	Date st;
	Date et;

	try {
	    et = getSimpleDateFormat(defaultPattern).parse(endTime);
	    st = getSimpleDateFormat(defaultPattern).parse(startTime);
	} catch (ParseException e) {
	    return null;
	}

	Calendar ca1 = Calendar.getInstance();
	Calendar ca2 = Calendar.getInstance();
	ca1.setTime(st);
	ca2.setTime(et);

	int ca1Year = ca1.get(Calendar.YEAR);
	int ca1Month = ca1.get(Calendar.MONTH);

	int ca2Year = ca2.get(Calendar.YEAR);
	int ca2Month = ca2.get(Calendar.MONTH);
	int countMonth;// 这个是用来计算得到有多少个月时间的一个整数,
	if (ca1Year == ca2Year) {
	    countMonth = ca2Month - ca1Month;
	} else {
	    countMonth = (ca2Year - ca1Year) * 12 + (ca2Month - ca1Month);
	}

	int months[][] = new int[countMonth + 1][2]; // 年月日二维数组

	for (int i = 0; i < countMonth + 1; i++) {
	    // 每次在原基础上累加一个月

	    months[i][0] = ca1.get(Calendar.YEAR);
	    months[i][1] = ca1.get(Calendar.MONTH);
	    months[i][1] += 1;
	    ca1.add(ca1.MONTH, 1);
	}

	return months;
    }

    /**
     * yyyy-MM-dd HH:mm 格式日期 转化 为 M月d日HH:mm 格式日期
     *
     * @param date
     *            String
     * @return String
     */
    public static String string2String(String date) throws ParseException {
	return date2String(dateString2Date(date, dateTimePattern), dateMonthHourPattern);
    }

    /**
     * Description:
     *
     * @param date
     * @param pattern
     * @return
     * @throws ParseException
     * 	    @Version1.0 2012-11-9 上午10:57:30 by 万久卫（jw.wan@zuche.com）
     */
    public static String string2String(String date, String pattern) throws ParseException {
	return date2String(dateString2Date(date), pattern);
    }

    /**
     * Description: 得到两个时间差
     *
     * @param startTime
     *            开始时间
     * @param toTime
     *            结束时间
     * @param pattern
     *            日期格式字符串
     * @return long 时间差 @Version1.0 2012-11-5 上午09:04:45 by
     *         万久卫（jw.wan@zuche.com）
     */
    public static long getDateDiff(String startTime, String toTime, String pattern) {
	long diff = getDateDiffLong(startTime, toTime, pattern);
	diff = diff / 1000 / 60;
	return diff;
    }

    /**
     * Description:
     *
     * @param startTime
     * @param toTime
     * @param pattern
     * @return @Version1.0 2012-11-9 上午10:25:23 by 万久卫（jw.wan@zuche.com）
     */
    public static long getDateDiffLong(String startTime, String toTime, String pattern) {
	long diff = 0l;
	if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(toTime)) {
	    SimpleDateFormat format = getSimpleDateFormat(pattern);
	    ParsePosition pos = new ParsePosition(0);
	    Date startTimeD = format.parse(startTime, pos);
	    pos.setIndex(0);
	    Date toTimeD = format.parse(toTime, pos);
	    if (startTimeD != null && toTimeD != null) {
		diff = startTimeD.getTime() - toTimeD.getTime();
	    }
	}
	return diff;
    }

    /**
     * Description: 得到两个时间差
     *
     * @param startTime
     *            开始时间
     * @param toTime
     *            结束时间
     * @return long 时间差 @Version1.0 2012-11-5 上午09:05:27 by
     *         万久卫（jw.wan@zuche.com）
     */
    public static long getDateDiff(String startTime, String toTime) {
	return getDateDiff(startTime, toTime, dateTimePattern);
    }

    /**
     * Description: 得到两个时间差
     *
     * @param startTimeD
     *            开始时间
     * @param toTime
     *            结束时间
     * @param pattern
     *            日期格式字符串
     * @return long 时间差 @Version1.0 2012-11-5 上午09:09:34 by
     *         万久卫（jw.wan@zuche.com）
     */
    public static long getDateDiff(Date startTimeD, String toTime, String pattern) {
	long diff;
	Date toTimeD = dateString2Date(toTime, pattern);
	diff = startTimeD.getTime() - toTimeD.getTime();
	return diff;
    }

    /**
     * Description:
     *
     * @param hour
     * @param minute
     * @return @Version1.0 2012-11-5 上午10:26:46 by 万久卫（jw.wan@zuche.com）
     */
    public static Integer getMinuteTotal(String hour, String minute) {
	return getMinuteTotal(Integer.parseInt(hour), Integer.parseInt(minute));
    }

    /**
     * Description:
     *
     * @param hour
     * @param minute
     * @return @Version1.0 2012-11-5 上午10:26:50 by 万久卫（jw.wan@zuche.com）
     */
    public static Integer getMinuteTotal(Integer hour, Integer minute) {
	return hour * 60 + minute;
    }

    private static SimpleDateFormat getSimpleDateFormat(String pattern) {
	SimpleDateFormat simpleDateFormat;
	HashMap<String, SimpleDateFormat> simpleDateFormatMap = customerMapThread.get();
	if (simpleDateFormatMap != null && simpleDateFormatMap.containsKey(pattern)) {
	    simpleDateFormat = simpleDateFormatMap.get(pattern);
	} else {
	    simpleDateFormat = new SimpleDateFormat(pattern);
	    if (simpleDateFormatMap == null) {
		simpleDateFormatMap = new HashMap<String, SimpleDateFormat>();
	    }
	    simpleDateFormatMap.put(pattern, simpleDateFormat);
	    customerMapThread.set(simpleDateFormatMap);
	}

	return simpleDateFormat;
    }


    /**
     * @Title dateCompareWithCurrtent
     * @Description 判断日期字符串与当前日期比较yyyyMMdd
     * @param compareDate
     * @return
     * @Author cui jixiang
     * @Date 2015年11月4日 下午6:39:35
     * @Return boolean 返回类型
     * @Throws
     */
    public static boolean dateCompareWithCurrtent(String compareDate) {
	boolean comResult = false;
	Date comDate = DateUtils.dateString2Date(compareDate + "235959", dateTimeYNDHMSPattern);
	Date toComDate = DateUtils.getNowDate();
	if (comDate.after(toComDate)) {
	    comResult = true;
	}
	return comResult;
    }

    public static String getYear_Month() {
	Calendar cal = Calendar.getInstance();
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
	return sdf.format(cal.getTime());
    }
	/**
	 *
	 * 功能：日期相减
	 *
	 * @pram startDate 开始时间 （输入为空时，默认为当前时间）
	 *
	 * @pram endDate 结束时间
	 * @return 获得两日期相减的间隔，单位：秒
	 *
	 */
	public static long getSubtractDate(String endDate, String startDate) {
		// 实例当前日期
		Calendar nowDate = Calendar.getInstance();

		Calendar calendar = Calendar.getInstance();
		try {
			// 日期格式化
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			// 开始时间输入不为空时，则为输入的时间

			if (startDate != null && !"".equals(startDate)) {
				Date start = dateFormat.parse(startDate);
				nowDate.setTime(start);
			}
			// 实例结束时间
			Date end = dateFormat.parse(endDate);
			calendar.setTime(end);
		} catch (ParseException e) {

			e.printStackTrace();
		}
		return nowDate.getTime().getTime() / 1000 - calendar.getTime().getTime() / 1000;
	}
}
